package zj.it.bhne.huanxin.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.EMContactListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hyphenate.exceptions.HyphenateException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import zj.it.bhne.huanxin.R;
import zj.it.bhne.huanxin.fragment.SetFragment;
import zj.it.bhne.huanxin.myuntils.HuanApplication;

public class HomeActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "HomeActivity";
    private EaseContactListFragment contactListFragment;
    private Context context;
    private TextView btn_conversation;
    private TextView unread_msg_number;
    private RelativeLayout btn_container_conversation;
    private Button btn_address_list;
    private TextView unread_address_number;
    private RelativeLayout btn_container_address_list;
    private Button btn_setting;
    private RelativeLayout btn_container_setting;
    private LinearLayout main_bottom;
    private RelativeLayout fragment_container;
    private RelativeLayout mainLayout;
    private Map<String, EaseUser> easeUserMap = new HashMap<>();
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            easeUserMap = (Map<String, EaseUser>) msg.obj;
        }
    };
    private EaseConversationListFragment conversationListFragment = new EaseConversationListFragment();
    private int count;
    private EMMessageListener msgListener = new EMMessageListener() {

        @SuppressLint("SetTextI18n")
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //收到消息
            conversationListFragment.refresh();
            count = 0;
            Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
            for (String key : conversations.keySet()) {
                int cou = conversations.get(key).getUnreadMsgCount();
                count += cou;
            }
            if (count > 0) {
                unread_msg_number.setVisibility(View.VISIBLE);
                unread_msg_number.setText(count + "");
            } else {
                unread_msg_number.setVisibility(View.INVISIBLE);
            }
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            //消息被撤回
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        context = this;
        if (getIntent().getIntExtra("login", 0) == 1) {
            HuanApplication.setShortToast(context, "登录聊天服务器成功！");
        }
        initView();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        changeFragment(conversationListFragment);
        btn_conversation = findViewById(R.id.btn_conversation);
        btn_conversation.setOnClickListener(this);
        unread_msg_number = findViewById(R.id.unread_msg_numbers);
        unread_msg_number.setOnClickListener(this);
        btn_container_conversation = findViewById(R.id.btn_container_conversation);
        btn_container_conversation.setOnClickListener(this);
        btn_address_list = findViewById(R.id.btn_address_list);
        btn_address_list.setOnClickListener(this);
        unread_address_number = findViewById(R.id.unread_address_number);
        unread_address_number.setOnClickListener(this);
        btn_container_address_list = findViewById(R.id.btn_container_address_list);
        btn_container_address_list.setOnClickListener(this);
        btn_setting = findViewById(R.id.btn_setting);
        btn_setting.setOnClickListener(this);
        btn_container_setting = findViewById(R.id.btn_container_setting);
        btn_container_setting.setOnClickListener(this);
        main_bottom = findViewById(R.id.main_bottom);
        main_bottom.setOnClickListener(this);
        fragment_container = findViewById(R.id.fragment_container);
        fragment_container.setOnClickListener(this);
        mainLayout = findViewById(R.id.mainLayout);
        mainLayout.setOnClickListener(this);
        //注册一个监听连接状态的listener
        com.hyphenate.chat.EMClient.getInstance().addConnectionListener(new MyConnectionListener());
        // 上传 token 方法，token 是通过广播接收器接收到的
        EMClient.getInstance().sendHMSPushTokenToServer("100448627", "f8f245c3f8ba9c6be1e361dc3d1d6ae7");
        getMessage();
        getContacts();
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }

    @SuppressLint("SetTextI18n")
    private void getMessage() {

        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        for (String key : conversations.keySet()) {
            int cou = conversations.get(key).getUnreadMsgCount();
            count += cou;
        }

        if (count > 0) {
            unread_msg_number.setVisibility(View.VISIBLE);
            unread_msg_number.setText(count + "");
        } else {
            unread_msg_number.setVisibility(View.INVISIBLE);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //记得在不需要的时候移除listener，如在activity的onDestroy()时
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_conversation:
                getHuiHua();
                changeFragment(conversationListFragment);
                break;
            case R.id.btn_address_list:
                getTongXun();
                changeFragment(contactListFragment);
                break;
            case R.id.btn_setting:
                changeFragment(new SetFragment());

                break;
        }
    }


    /**
     * 通讯录fragment设置
     */
    private void getTongXun() {

        contactListFragment = new EaseContactListFragment();
        contactListFragment.setContactsMap(easeUserMap);
        contactListFragment.setActivity(AddFriendActivity.class);
        //设置item点击事件
        //Log.e("TAG", "onClick: " + getContacts().size());
        contactListFragment.setContactListItemClickListener(new EaseContactListFragment.EaseContactListItemClickListener() {
            @Override
            public void onListItemClicked(EaseUser user) {
                startActivity(new Intent(HomeActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_USER_ID, user.getUsername()));
            }
        });

        EMClient.getInstance().contactManager().setContactListener(new EMContactListener() {


            @Override
            public void onContactInvited(String username, String reason) {
                //收到好友邀请
                Log.e(TAG, "onContactInvited: " + username);

            }

            @Override
            public void onFriendRequestAccepted(String s) {
                Log.e(TAG, "onFriendRequestAccepted: " + s);
            }

            @Override
            public void onFriendRequestDeclined(String s) {
                Log.e(TAG, "onFriendRequestDeclined: " + s);
            }

            @Override
            public void onContactDeleted(String username) {
                //被删除时回调此方法
                Log.e(TAG, "onContactDeleted: " + username);
            }


            @Override
            public void onContactAdded(String username) {
                //增加了联系人时回调此方法
                Log.e(TAG, "onContactAdded: " + username);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        contactListFragment.setContactsMap(easeUserMap);
                        contactListFragment.refresh();
                    }
                }).start();

            }
        });

    }

    /**
     * 会话fragment设置
     */
    private void getHuiHua() {
        conversationListFragment.setConversationListItemClickListener(new EaseConversationListFragment.EaseConversationListItemClickListener() {
            @Override
            public void onListItemClicked(EMConversation conversation) {
                startActivity(new Intent(HomeActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_USER_ID, conversation.getAllMessages().get(0).getUserName()));
            }
        });
    }


    private void getContacts() {
        final Map<String, EaseUser> easeUserMap = new HashMap<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    List<String> userNames = EMClient.getInstance().contactManager().getAllContactsFromServer();
                    if (userNames != null) {
                        for (int i = 0; i < userNames.size(); i++) {
                            easeUserMap.put(userNames.get(i), new EaseUser(userNames.get(i)));
                        }
                        Message message = new Message();
                        message.what = 200;
                        message.obj = easeUserMap;
                        handler.sendMessage(message);
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    private void changeFragment(Fragment fragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.commit();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    //实现ConnectionListener接口
    private class MyConnectionListener implements com.hyphenate.EMConnectionListener {
        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    switch (error) {
                        case com.hyphenate.EMError.USER_REMOVED:
                            // 显示帐号已经被移除
                            HuanApplication.setShortToast(HomeActivity.this, "帐号已经被移除");
                            break;
                        case com.hyphenate.EMError.USER_LOGIN_ANOTHER_DEVICE:
                            // 显示帐号在其他设备登录
                            HuanApplication.setShortToast(HomeActivity.this, "帐号在其他设备登录");
                            break;
                        default:
                            if (com.hyphenate.util.NetUtils.hasNetwork(HomeActivity.this)) {
                                //连接不到聊天服务器
                                HuanApplication.setShortToast(HomeActivity.this, "连接不到聊天服务器");
                            } else {
                                //当前网络不可用，请检查网络设置
                                HuanApplication.setShortToast(HomeActivity.this, "当前网络不可用，请检查网络设置");
                            }
                            break;
                    }
                }
            });
        }
    }
}
